package com.zhao.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhao.pojo.User;
import com.zhao.pojo.Wallet;
import com.zhao.service.UserService;
import com.zhao.service.WalletService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    @Autowired
    WalletService walletService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权+doGetAuthorizationInfo");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //info.addStringPermission("user:add");
        Subject subject = SecurityUtils.getSubject();
        //拿到User对象
        User currentUser = (User) subject.getPrincipal();
        for (String perm: currentUser.getPerms()) {
            info.addStringPermission(perm);
        }
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("认证+doGetAuthenticationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        User user = userService.getOne(new QueryWrapper<User>().eq("user_name", userToken.getUsername()).eq("status","正常"));

        //当前realm对象的name
        String realmName = getName();
        //盐值
        ByteSource credentialsSalt = null;
        System.out.println(user!=null);
        if (user==null){//用户是否存在
            return null;//抛出异常 UnknownAccountException
        }else {
            //盐值
            credentialsSalt = ByteSource.Util.bytes(user.getSalt());
            //获取用户的权限信息
            user.setPerms(userService.getByIdPerms(user.getUserId()));

            Wallet wallet = walletService.getOne(new QueryWrapper<Wallet>().eq("uid", user.getUserId()));
            user.setWallet(wallet);
        }
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);

        //密码认证：shiro做
        return new SimpleAuthenticationInfo(user,user.getUserPass(),credentialsSalt,realmName);
    }
}
